﻿using System;
using System.Net;
using System.Net.Http;
using System.Text;
using Core.Ndatax.Domain.Ris.CancelRegisterOrCheckInResult;
using Core.Ndatax.Domain.Ris.CheckInOrRegister;
using Core.Ndatax.Domain.Ris.CheckInResult;
using Core.Ndatax.Domain.Ris.RegisterResult;
using Core.Ndatax.Domain.Ris.UpdateRegisterResult;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Xman.Extensions.Core;

namespace Core.Ndatax.Domain
{
    public class RisServer
    {
        private readonly ILogger<RisServer> _logger;
        private readonly RisOptions _options;
        private readonly HttpClient _client;

        public RisServer(HttpClient client, ILogger<RisServer> logger, IOptions<RisOptions> options)
        {
            _client = client;
            _logger = logger;
            _options = options.Value;
        }

        /// <summary>
        /// 报道接口
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<CheckInResult> CheckInAsync(CheckInOrRegisterDto input)
        {
            try
            {
                if (_options.CheckInUrl.IsNullOrEmpty())
                {
                    throw new Exception("请求地址未正确配置");
                }

                _logger.LogInformation($"发送的参数:{input.ToJson()}");
                var sendcontent = new StringContent(input.ToJson(), Encoding.UTF8, "application/json");
                var response = await _client.PostAsync(_options.CheckInUrl, sendcontent);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new Exception($"Http状态异常，{response.StatusCode}");
                }

                var responsestr = await response.Content.ReadAsStringAsync();
                _logger.LogInformation($"结果:{responsestr}");
                var result = JsonConvert.DeserializeObject<CheckInResult>(responsestr);
                _logger.LogInformation("报到后解析result，" + result.Result);
                if (result!=null && result.Result)
                {
                    _logger.LogInformation("进入到详细检测，list的个数：" + result.RespData.list.Count() + "---------" + result.RespData.list.ToJson());
                    foreach(var item in result.RespData.list)
                    {
                        _logger.LogInformation($@"循环获取过滤结果异常数据，result：-----------{ item.requisitionState.result}--------message----------{item.requisitionState.message }");
                    }
                    var list = result.RespData.list.Where(t => t.requisitionState.result == 0);
                    _logger.LogInformation("过滤结果异常数据，个数：" + list.Count() + "----------" + list.ToJson());
                    if (list.Any())
                    {
                        _logger.LogInformation("进入到拼接异常数据，异常个数："+list.Count());
                        result.Result = false;
                        result.Error = list.Select(t => t.requisitionState.message).Distinct().ToList().ToStringJoin();
                        _logger.LogInformation("报到后解析result有异常-------------------"+ result.Error);
                    }
                }
                _logger.LogInformation("返回的result-------------------" + result.ToJson());
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError($"调用异常，{ex}");
                return new CheckInResult() { Error = "调用异常：" + ex.Message };
            }
        }



        /// <summary>
        /// 登记接口
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<RegisterResult> RegisterAsync(CheckInOrRegisterDto input)
        {
            try
            {
                if (_options.RegisterUrl.IsNullOrEmpty())
                {
                    throw new Exception("请求地址未正确配置");
                }

                _logger.LogInformation($"发送的参数:{input.ToJson()}");
                var sendcontent = new StringContent(input.ToJson(), Encoding.UTF8, "application/json");
                var response = await _client.PostAsync(_options.RegisterUrl, sendcontent);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    _logger.LogInformation($"Http状态异常，{response.StatusCode}");
                    return new RegisterResult() { Error = "网络异常" };

                }
                else
                {
                    var responsestr = await response.Content.ReadAsStringAsync();
                    _logger.LogInformation($"结果:{responsestr}");
                    var result = JsonConvert.DeserializeObject<RegisterResult>(responsestr);
                    return result;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"调用异常，{ex}");
                return new RegisterResult() { Error = "调用异常：" + ex.Message };
            }
        }


        /// <summary>
        /// 取消登记/报到接口
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<CancelRegisterOrCheckInResult> CancelRegisterOrCheckInAsync(Ris.CancelRegisterOrCheckInDto.CancelRegisterOrCheckInDto input)
        {
            try
            {
                if (_options.CancelRegisterUrl.IsNullOrEmpty())
                {
                    throw new Exception("请求地址未正确配置");
                }

                _logger.LogInformation($"发送的参数:{input.ToJson()}");
                var sendcontent = new StringContent(input.ToJson(), Encoding.UTF8, "application/json");
                var response = await _client.PostAsync(_options.CancelRegisterUrl, sendcontent);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    _logger.LogInformation($"Http状态异常，{response.StatusCode}");
                    return new CancelRegisterOrCheckInResult() { Error = "网络异常" };

                }

                var responsestr = await response.Content.ReadAsStringAsync();
                _logger.LogInformation($"结果:{responsestr}");
                var result = JsonConvert.DeserializeObject<CancelRegisterOrCheckInResult>(responsestr);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError($"调用异常，{ex}");
                return new CancelRegisterOrCheckInResult() { Error = "调用异常：" + ex.Message };
            }
        }


        /// <summary>
        /// 修改登记接口
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Ris.UpdateRegisterResult.UpdateRegisterResult> UpdateRegisterAsync(Ris.UpdateRegisterDto.UpdateRegisterDto input)
        {
            try
            {
                if (_options.UpdateRegisterUrl.IsNullOrEmpty())
                {
                    throw new Exception("请求地址未正确配置");
                }

                _logger.LogInformation($"发送的参数:{input.ToJson()}");
                var sendcontent = new StringContent(input.ToJson(), Encoding.UTF8, "application/json");
                var response = await _client.PostAsync(_options.UpdateRegisterUrl, sendcontent);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    _logger.LogInformation($"Http状态异常，{response.StatusCode}");
                    return new UpdateRegisterResult() { Error = "网络异常" };
                }
                else
                {
                    var responsestr = await response.Content.ReadAsStringAsync();
                    _logger.LogInformation($"结果:{responsestr}");
                    var result = JsonConvert.DeserializeObject<Ris.UpdateRegisterResult.UpdateRegisterResult>(responsestr);
                    return result;

                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"调用异常，{ex}");
                return new UpdateRegisterResult() { Error = "调用异常：" + ex.Message };
            }
        }

    }
}
